require "digest/sha1"

class User < ActiveRecord::Base
	has_many :panels

	validates_presence_of :userName
	validates_uniqueness_of :userName
	
	attr_accessor :password_confirmation
	validates_confirmation_of :password

	def validate
		errors.add_to_base("Missing password") if password.blank?
	end
	
	def password
		@password
	end

	def password=(pwd)
		@password = pwd
		create_new_salt
		self.hashed_password = User.encrypted_password(self.password, self.salt)
	end

	def self.authenticate(userName, password)
		user = self.find_by_userName(userName)
		if user
			expected_password = encrypted_password(password, user.salt)
			if user.hashed_password != expected_password
				user = nil
			end
		end
		user
	end

	def signin
		if request.post?
		session[:user] = User.authenticate(params[:userName], params[:password]).id
		redirect_to :action => session[:intended_action],
								:controller => session[:intended_controller]
		end
	end

	def cheak_user
	
	end

	def signout
		session[:user] = nil
		redirect_to(:controller => :board, :action => :index, :id => user.userName) 
	end

	private

	def self.encrypted_password(password,salt)
		string_to_hash = password + "pyrenees_onesup" + salt
		Digest::SHA1.hexdigest(string_to_hash)
	end

	def create_new_salt
		self.salt = self.object_id.to_s + rand.to_s
	end

end
